import * as fyStorage from '@/utils/storageUtils.js'
import { getUserInfo, getSelfGroupList, getSelfGroupCountInfo, getVipItemCount } from '@/utils/http.js'
import baseconfig from '@/config.js'
export default {
	namespaced: true,
	state: {
		token: fyStorage.getToken(),
		userInfo: fyStorage.getUserInfo(),
		selfGroup: [],
		groupCount: {
			area: 0,
			country: 0,
			all: 0,
			total: 0
		},
		vipCount: {
			upload: 0
		}
	},
	getters:{
		userInfo:state=>{
			if(!state.userInfo){
				
				return {avatar:''}
			}
			return state.userInfo
		}
	},
	mutations: {
		saveToken(state, token) {
			fyStorage.setToken(token)
			state.token = token
		},
		setUser(state, user) {
			if (user) {
				user.avatar = ''
				if (user.imgsrc) {
					user.avatar = baseconfig.api_url + user.imgsrc + '?t=' + new Date()
				}
				var local = user.ipplace.split(" ")
				user.province = local[1]
				user.city = local[2]
			}
			fyStorage.setUserInfo(user)
			state.userInfo = user
		},
		setSelfGroup(state, group) {
			state.selfGroup = group
		},
		setGroupCount(state, data) {
			const { count1, count2, count0 } = data
			state.groupCount.country = count1
			state.groupCount.area = count2
			state.groupCount.all = count0
			state.groupCount.total = count1 + count2 + count0
		},
		setVipCount(state,data){
			state.vipCount=data
		}
	},
	actions: {
		initUserData({  dispatch }) {

			dispatch('reloadUser')
			dispatch('reloaduserGroup')
			dispatch('reloadVipCount')
		},
		async reloadVipCount({state, commit }) {
			if (state.token) {
				const { data } = await getVipItemCount()
				commit('setVipCount', data)
			} else {
				const data = { upload: 0 }
				commit('setVipCount', data)
			}

		},
		reloaduserGroup({ state, commit }) {
			if (state.token) {
				getSelfGroupList().then(res => {
					const { data, total, rows, count } = res.data
					rows.forEach(arr => {
						arr.avatar = baseconfig.api_url + arr.imgsrc
						arr.img_contact = baseconfig.api_url + arr.contacts
						arr.isJoin = true
					})
					commit('setSelfGroup', rows)
				})
				getSelfGroupCountInfo().then(res => {
					commit('setGroupCount', res.data)
				})
			}

		},
		reloadUser({ state, commit, dispatch }) {
			if (state.token) {
				getUserInfo().then(res => {
					const { code, data } = res
					if (code == 200) {
						fyStorage.setUserInfo(data)
						commit('setUser', data)
					} else {
						dispatch('loginOut')
					}

				})
			}

		},
		userLogin({ commit, dispatch }, data) {
			commit('saveToken', data.token)
			commit('setUser', data)
			dispatch('reloaduserGroup')
		},
		loginOut({ commit, dispatch }) {
			fyStorage.clearToken()
			fyStorage.clearUserInfo()
			commit('saveToken', '')
			commit('setSelfGroup', [])
			commit('setUser', null)

			commit('setGroupCount', {
				area: 0,
				country: 0,
				all: 0,
				total: 0
			})

			dispatch('socket/closeSocket', {}, { root: true })
		}
	}
}